<template>
  <el-row>
    <el-col :span="16" :offset="4">
      <el-form ref="form" :model="newsInfo" :rules="rules" label-position="right" label-width="100px">
        <el-form-item label="新闻标题" prop="title">
          <el-input v-model="newsInfo.title" placeholder="请输入新闻标题"></el-input>
        </el-form-item >
        <el-form-item label="新闻作者" prop="author">
          <el-input v-model="newsInfo.author" placeholder="请输入新闻作者"></el-input>
        </el-form-item >
        <el-form-item label="新闻简介" prop="introduction">
          <el-input type="textarea" v-model="newsInfo.introduction" :rows="2" maxlength="50" show-word-limit placeholder="请输入新闻简介"/>
        </el-form-item>
        <el-form-item label="新闻内容" prop="content">
          <el-input type="textarea"
                    v-model="newsInfo.content"
                    show-word-limit placeholder="请输入新闻内容"
                    :autosize="{ minRows: 2, maxRows: 4}"
          />
        </el-form-item>
        <el-form-item label="发布日期" prop="releaseDate" >
          <el-date-picker
            v-model="newsInfo.releaseDate" placeholder="请选择发布日期" format="yyyy年MM月dd日" value-format="yyyy-MM-dd" >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="新闻类型" prop="types">
          <el-select v-model="newsInfo.types" placeholder="请选择" multiple>
            <el-option v-for="ti in news.type" :key="ti.typeId" :label="ti.typeName" :value="ti.typeId"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="新闻封面" prop="cover">
          <el-upload ref="pictureUpload"
            class="avatar-uploader"
            :action="uploadPath"
            list-type="picture-card" :headers="uploadHeader"
            :show-file-list="true"
            :before-upload="beforeUpload"
            :on-success="uploadSuccess" :limit="1" :file-list="fileList">
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" height="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">保存</el-button>
          <el-button type="warning" @click="onReset">返回</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script>
const initNews = {
  newsId: '',
  title: '',
  introduction: '',
  content: '',
  releaseDate: '',
  types: [],
  cover: ''
}

export default {
  name: 'NewsEdit',
  data () {
    return {
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      uploadHeader: {
        token: ''
      },
      uploadPath: process.env.VUE_APP_BASE_API + '/upload',
      newsInfo: { ...initNews },
      props: { multiple: true },
      news: {
        cover: '',
        type: [],
        status: [{
          value: 0,
          label: '禁用'
        }, {
          value: 1,
          label: '可用'
        }]
      },
      imageUrl: '',
      rules: {
        title: [{ required: true, message: '请输入新闻标题', trigger: 'blur' }],
        author: [{ required: true, message: '请输入新闻标题', trigger: 'blur' }],
        introduction: [{ required: true, message: '请输入新闻简介', trigger: 'blur' }],
        content: [{ required: true, message: '请输入新闻内容', trigger: 'blur' }],
        releaseDate: [{ required: true, message: '请输入新闻内容', trigger: 'blur' }],
        types: [{ required: true, message: '请选择新闻状态', trigger: 'change' }],
        cover: [{ required: true, message: '请选择新闻封面', trigger: 'change' }]
      }
    }
  },
  methods: {
    handleRemove (file) {
      this.$confirm('您确定要移除吗?', '询问').then(() => {
        this.$refs.pictureUpload.handleRemove(file)
      })
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    beforeUpload (file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isImage) {
        this.$message.error('文件格式不正确')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('图片大小不能超过2M')
      }
      return isImage && isLt2M
    },
    uploadSuccess (data) {
      if (data.code === 200) {
        this.newsInfo.cover = data.data
      }
    },
    onSubmit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$axios.post('sys/news/update/', this.newsInfo).then(({ data }) => {
            if (data.code === 200) {
              this.$alert('保存成功').then(() => {
                this.$router.push('news')
              })
            } else {
              this.$alert('保存失败')
            }
          })
        }
      })
    },
    onReset () {
      this.newsInfo = { ...initNews }
      this.$refs.pictureUpload.clearFiles()
      this.$router.push('/news')
    },
    getNewsTypeList () {
      this.$http.get('sys/type/news/select').then(({ data }) => {
        if (data.code === 200) {
          this.news.type = data.data.list
        }
      })
    },
    init () {
      if (this.$route.query.newsId) {
        this.$http.get('/sys/news/info/' + this.$route.query.newsId).then(({ data }) => {
          console.log(data.data)
          const news = data.data.news
          const type = data.data.type
          const typeIds = []
          for (let i = 0; i < type.length; i++) {
            if (type[i].status === 1) { typeIds.push(type[i].typeId) }
          }
          console.log(typeIds)
          if (data.code === 200) {
            this.newsInfo = {
              newsId: news.newsId,
              title: news.title,
              cover: news.cover,
              author: news.author,
              introduction: news.introduction,
              content: news.content,
              releaseDate: news.releaseDate,
              types: typeIds
            }
            this.fileList.push({
              name: this.newsInfo.cover,
              url: `${process.env.VUE_APP_BASE_API}/img/${this.newsInfo.cover}`
            })
            // console.log(this.fileList)
          }
        })
      }
    }
  },
  created () {
    this.$nextTick(() => {
      this.getNewsTypeList()
      this.init()
      this.uploadHeader.token = this.$cookies.get('token')
    })
  }
}

</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
